package org.cainiao.io.netty.other.transport;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.util.CharsetUtil;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import static io.netty.buffer.Unpooled.copiedBuffer;

/**
 * <br />
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
public class CommonTest {

    public static void main(String[] args) {
        Channel channel = null;
        singleThread(channel);
        multiThread(channel);
    }

    private static void singleThread(Channel channel) {
        ChannelFuture cf = channel.writeAndFlush(copiedBuffer("your data", CharsetUtil.UTF_8));
        cf.addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                System.out.println("Write successful");
            } else {
                System.err.println("Write error");
                future.cause().printStackTrace();
            }
        });
    }

    private static void multiThread(Channel channel) {
        final ByteBuf byteBuf = copiedBuffer("your data", CharsetUtil.UTF_8).retain();
        Runnable writer = () -> channel.writeAndFlush(byteBuf.duplicate());
        Executor executor = Executors.newCachedThreadPool();
        // write in one thread
        executor.execute(writer);
        // write in another thread
        executor.execute(writer);
        // ...
    }

}
